package com.whacos.common.aspect;

import com.whacos.common.enums.Constant;
import com.whacos.common.shiro.ShiroUtils;
import com.whacos.common.utils.HttpContextUtils;
import com.whacos.common.utils.IPUtils;
import com.whacos.common.utils.JSONUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.modules.system.entity.Log;
import com.whacos.modules.system.entity.SysUser;
import com.whacos.modules.system.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author xiongdun
 * @description LogAspect
 * @since 2018/11/17 17:11
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private LogService logService;


    @Pointcut("@annotation(com.whacos.common.annotations.Log)")
    public void logPointCut() {
        // logger 日志切点
    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        saveLog(point, time);
        return result;
    }

    /**
     * 保存日志
     *
     * @param joinPoint
     * @param time
     * @throws InterruptedException
     */
    private void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log sysLog = new Log();
        com.whacos.common.annotations.Log log = method.getAnnotation(com.whacos.common.annotations.Log.class);
        if (ObjectUtils.isNotEmpty(log)) {
            // 注解上的描述
            sysLog.setOperation(log.value());
        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = "Parameters is empty !";
            if (ObjectUtils.isNotEmpty(args) && ObjectUtils.isNotEmpty(args[0])) {
                params = JSONUtils.beanToJson(args[0]);
                if (StringUtils.isNotEmpty(params) && params.length() > 4999) {
                    params = params.substring(0, 4999);
                }
            }
            sysLog.setParams(null);
        } catch (Exception e) {
            logger.error("保存日志异常，异常原因：" + e.getMessage(), e);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        String ip = IPUtils.getIpAddr(request);
        sysLog.setIpAddress(StringUtils.isNotEmpty(ip) ? ip : "127.0.0.1");
        // 用户名
        SysUser currentUser = ShiroUtils.getUser();
        if (ObjectUtils.isEmpty(currentUser)) {
            if (ObjectUtils.isNotEmpty(sysLog.getParams())) {
                sysLog.setCreatedBy(Constant.DEFAULT_USER_ID);
                sysLog.setCreatedUsername(sysLog.getParams());
            } else {
                sysLog.setCreatedBy(Constant.DEFAULT_USER_ID);
                sysLog.setCreatedUsername("获取用户信息为空");
            }
            //sysLog.setCreateBy(Constant.DEFAULT_USER_ID);
        } else {
            sysLog.setCreatedUsername(ShiroUtils.getUser().getUsername());
        }
        sysLog.setCostTime((int) time);
        // 保存系统日志
        this.logService.add(sysLog);
    }
}
